import { storeToRefs } from 'pinia'

import { useAppStore } from '@/stores/modules/app'

const { device } = storeToRefs(useAppStore())

const funcMap = new Map() // 用于缓存回调方法

/**
 * 调用原生方法通用方法
 * @param type 需要被调用的服务名
 * @param params 调用服务的参数
 * @param func 回调方法
 */
export const callLocal = (
  type: string,
  params?: string,
  func?: () => never
) => {
  try {
    let uuid: string = ''
    if (func) {
      uuid = `callback${new Date().getTime()}`
      funcMap.set(uuid, func)
    }

    if (device.value === 'android') {
      if (uuid) {
        window.AndroidJs.callNative(type, params ? params : '', uuid)
      } else {
        window.AndroidJs.callNative(type, params ? params : '', '')
      }
    }
    if (device.value === 'ios') {
      const data = {
        type: type,
        params: params ? JSON.parse(params) : '',
        uuid: uuid ? uuid : '',
      }
      window.webkit.messageHandlers.callNative.postMessage(JSON.stringify(data))
    }
  } catch (error) {
    throw new Error('bridge error' + error.message)
  }
}

/**
 * 异步调用原生方法
 */
export const asyncCallLocal = (type: string, params: string) => {
  return new Promise((resolve) =>
    callLocal(type, params, (data) => resolve(data))
  )
}

/**
 * h5中定义的回调函数，用于被原生调用
 * @param data  回传的参数
 * @param uuid   回传的定义的回调的签名
 */
window.callbackFun = (data: string, uuid: string) => {
  const getFunc = funcMap.get(uuid)
  getFunc(data)
  funcMap.delete(uuid)
}
